package org.hy.corn_task.utils;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.hy.corn_task.enums.RequestStatus;
import org.hy.corn_task.pojo.StatisticRecord;
import org.hy.corn_task.pojo.entity.target.YsgzBdcR1;
import org.hy.corn_task.pojo.entity.target.YsgzBdcR2;
import org.hy.corn_task.service.target.YsgzBdcR1Service;
import org.hy.corn_task.service.target.YsgzBdcR2Service;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Component
public class SaveReqData {

    @Resource
    public YsgzBdcR1Service ysgzBdcR1Service;
    @Resource
    public YsgzBdcR2Service ysgzBdcR2Service;

    public void saveData1(JSONObject jsonObject, Integer saveBatchSize) {
        List<YsgzBdcR1> result = new ArrayList<>();
        JSONArray objects = JSONUtil.parseArray(jsonObject.get("data"));
        for (Object objectData : objects) {
            YsgzBdcR1 ysgz_bdc_r1 = JSONUtil.toBean(objectData.toString(), YsgzBdcR1.class);
            result.add(ysgz_bdc_r1);
        }

        boolean flag = ysgzBdcR1Service.saveBatch(result, saveBatchSize);
        if (!flag) {
            throw new RuntimeException("数据入库失败");
        }
    }

    public void saveData2(JSONObject jsonObject, Integer saveBatchSize) {
        List<YsgzBdcR2> result = new ArrayList<>();
        JSONArray objects = JSONUtil.parseArray(jsonObject.get("data"));
        for (Object objectData : objects) {
            YsgzBdcR2 ysgz_bdc_r2 = JSONUtil.toBean(objectData.toString(), YsgzBdcR2.class);
            result.add(ysgz_bdc_r2);
        }
        boolean flag = ysgzBdcR2Service.saveBatch(result, saveBatchSize);
        if (!flag) {
            throw new RuntimeException("数据入库失败");
        }
    }

    public void validData(JSONObject jsonObject, StatisticRecord statisticRecord) {
        if (null == jsonObject) {
            statisticRecord.setStatus(RequestStatus.FAIL.getCode());
            throw new RuntimeException("数据源请求失败！");
        }
        Object data = jsonObject.get("data");
        if (Objects.isNull(data)) {
            statisticRecord.setStatus(RequestStatus.FAIL.getCode());
            throw new RuntimeException("数据源请求失败！");
        }
        if (data instanceof JSONArray) {
            JSONArray data1 = (JSONArray) data;
            if (data1.isEmpty()) {
                statisticRecord.setStatus(RequestStatus.EMPTY.getCode());
                throw new RuntimeException("数据查询为空！");
            }
        }
    }
}
